package com.itheima.controller;

import com.itheima.pojo.HmArticles;
import com.itheima.service.ArticlesService;
import com.itheima.util.Id;
import com.itheima.util.PageResult;
import com.itheima.util.Success;
import com.itheima.util.Token;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.List;

@RestController
@RequestMapping("/articles")
public class ArticlesController {
    @Autowired
    private ArticlesService articlesService;
    @Autowired
    private HttpServletRequest request;
    //分页查询
    @GetMapping
    public PageResult findByPage(Integer page , Integer pagesize ,String keyword,Integer state) throws ParseException {
        PageResult list = articlesService.findPage(page,pagesize,keyword,state);
        return list;
    }
    //文章添加
    @PostMapping
    public Id addArticles(@RequestBody HmArticles hmArticles){
        String cookie = request.getHeader("Authorization");
        String[] split = cookie.split(" ");
        Integer id = articlesService.add(hmArticles,split[1]);
        return new Id(id);
    }
    //文章禁用/启用
    @PostMapping("/{id}/{state}")
    public Success Update(@PathVariable Integer id, @PathVariable Integer state){
        boolean flag = articlesService.Update(id,state);
        return new Success(flag);
    }
    //文章删除
    @DeleteMapping("/{id}")
    public Success Delete(@PathVariable Integer id){
        boolean flag = articlesService.delete(id);
        return new Success(flag);
    }
    //文章编辑
    @PutMapping("/{id}")
    public Success UpdateWen(@PathVariable Integer id,@RequestBody HmArticles hmArticles){
        boolean flag = articlesService.updateWen(id,hmArticles);
        return new Success(flag);
    }
    //文章详情
    @GetMapping("/{id}")
    public HmArticles find(@PathVariable Integer id){
        HmArticles hm = articlesService.find(id);
        return hm;
    }
}
